<template>
  <div class="container">
    <el-dialog :visible.sync="dialogVisible" width="25%" :before-close="cancel">
      <template #title>
        <span style="color: white">新增标签</span>
      </template>
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="所属学科" v-if="!this.subjectID">
          <el-select
            v-model="addForm.subjectID"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.subjectName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <el-input
            v-model="addForm.tagName"
            placeholder="请输入标签名称"
            @blur="addForm.tagName = $event.target.value.trim()"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="btnOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, detail } from '../../api/hmmm/subjects'
import { add } from '../../api/hmmm/tags'
export default {
  props: {
    dialogVisible: { type: Boolean, default: false },
    subjectID: { type: [Number, String] },
    tableData: { type: Array } // 标签列表数据
  },
  data () {
    return {
      // 学科目录
      subjectList: [], // 学科列表数据
      // 表单数据
      addForm: { tagName: '', subjectID: '', subjectName: '' },
      // 校验规则
      addFormRules: {
        tagName: [
          { required: true, message: '请输入标签名称', trigger: 'blur' }
        ]
      }
    }
  },
  async mounted () {
    // 请求接口拿到学科目录
    const { data } = await list()
    this.subjectList = data.items
    // console.log(this.subjectList)
  },
  methods: {
    // 取消添加
    cancel () {
      this.$emit('update:dialogVisible', false)
      this.$refs.addFormRef.resetFields()
      this.addForm = { subjectName: '', tagName: '' }
    },
    // 确定添加
    async btnOk () {
      await this.$refs.addFormRef.validate()
      if (this.subjectID) {
        const { data } = await detail({ id: this.subjectID })
        this.addForm.subjectName = data.subjectName
        this.addForm.subjectID = this.subjectID - 0

        await add({ ...this.addForm })
        this.$emit('getTagsList', this.addForm.subjectID)
      } else {
        await add({ ...this.addForm })
        this.$emit('getTagsList')
      }
      if (this.addForm.subjectID) {
        this.$message.success('添加成功！')
        this.cancel()
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
